package com.nio.netty.dubborpc.netty;

import com.nio.netty.dubborpc.provider.HelloServiceImp;
import com.nio.netty.dubborpc.pubinterface.HelloService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

/*服务器的handler比较简单*/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /*获取客户端发送的消息，并调用服务*/
        System.out.printf("[%tF %<tT] msg:"+msg+"\n",new Date());
        /*客户端在调用服务器的服务的时候，我们需要定义一个协议*/
        /*比如我们要求  每次发消息的时候 都必须以某个字符串开头 "HelloService#hello#"*/
        if (msg.toString().startsWith("HelloService#hello#")) {
            String hello = new HelloServiceImp().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(hello);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
